<script setup>
import { ref } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import { showToast } from 'vant';
import { areaList } from '@vant/area-data';
import { useAddressStore } from '../../stores/address';

const router = useRouter();
const route = useRoute();
const addressStore = useAddressStore();
const editForm = ref({});

// 编辑按钮
// 找到当前编辑的地址  有id  就编辑 没有id 就新增
const curEdit = addressStore.addressList.find(item => item.id == route.query.id)
if(curEdit){
    editForm.value = {...curEdit}
}else{
    editForm.value = {
        name: '',
        tel: '',
        address: '',
        isDefault: false
    }
}

// 新增 保存按钮
const onSave = (info) => {
    console.log(info)
    if(route.query.id){
        addressStore.editAddress(info)
        showToast('编辑成功')
        router.push('/address')
    }else{
        addressStore.addAddress(info)
        showToast('新增成功')
        router.push('/address')
    }

};
// 删除 按钮
const onDelete = () =>{
    addressStore.delAddress(route.query.id)
    showToast('删除成功')
    router.push('/address')
}

</script>

<template>
    <van-address-edit
        :address-info="editForm"
        :area-list="areaList"
        :show-delete="Boolean(route.query.id)"
        show-set-default
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
    />
</template>

<style lang="scss" scoped>

</style>